var dlg = $('#dlg');
var dlgIndex;
var jdt = $('#jdt');
var jdtIndex;
var ctxPath = $('body').attr('ctxPath');
var charts1;
var charts4;

/**
 * 获取xData.一天的所有 小时:分钟. 5分钟为间隔.
 * 区间00:00 - 23:59.
 * 24*60 = 1440 数组元素最大数
 */
var getXData = function () {
    var date = new Date(); //'2019-04-09 23:59:04'
    var nowHour = date.getHours(); //当前时刻
    var nowMin = date.getMinutes(); //当前分钟
    //console.log(nowHour,nowMin,date.toLocaleString());
    var xData = [];
    //循环小时.
    for (var i = 0; i <= nowHour; i++) {
        //循环分钟.
        for (var j = 0; j <= 59; j++) {
            //判断.如果i为当前小时.则需要判断当前的分钟
            if (i == nowHour) {
                if (j <= nowMin) {
                    //时刻为0-9
                    if (i < 10) {
                        //分钟为0-9
                        if (j < 10) {
                            if (j % 5 == 0) {
                                xData.push('0' + i + ':0' + j);
                            }
                        } else {
                            if (j % 5 == 0) {
                                xData.push('0' + i + ':' + j);
                            }
                        }
                    } else {
                        //分钟为0-9
                        if (j < 10) {
                            if (j % 5 == 0) {
                                xData.push(i + ':0' + j);
                            }
                        } else {
                            if (j % 5 == 0) {
                                xData.push(i + ':' + j);
                            }
                        }
                    }
                }
            } else {
                //时刻为0-9
                if (i < 10) {
                    //分钟为0-9
                    if (j < 10) {
                        if (j % 5 == 0) {
                            xData.push('0' + i + ':0' + j);
                        }
                    } else {
                        if (j % 5 == 0) {
                            xData.push('0' + i + ':' + j);
                        }
                    }
                } else {
                    //分钟为0-9
                    if (j < 10) {
                        if (j % 5 == 0) {
                            xData.push(i + ':0' + j);
                        }
                    } else {
                        if (j % 5 == 0) {
                            xData.push(i + ':' + j);
                        }
                    }
                }
            }
        }
    }
    return xData;
}


$(function () {

    $.ajax({
        'url': ctxPath + '/power/supply/data?_t=' + new Date().getTime(),
        'type': 'post',
        'dataType': 'json',
        'success': function (res) {
            if (res.statusCode == 200) {
                var second = res.data.second;
                var capacity = res.data.capacity;
                var loading = res.data.loading;

                charts1 = echarts.init(document.getElementById('gd_fh'), 'dark');
                var option1 = {
                    title: {
                        text: '供电能力及负荷曲线',
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['供电能力', '负荷曲线']
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        splitLine: {
                            show: false
                        },
                        data: second
                    },
                    yAxis: {
                        type: 'value',
                        splitLine: {
                            show: false
                        },
                    },
                    series: [{
                        symbol: "none",
                        name: '负荷曲线',
                        data: loading,
                        type: 'line',
                        areaStyle: {},
                        color: 'rgb(79,189,255)'
                    }, {
                        symbol: "none",
                        name: '供电能力',
                        data: capacity,
                        type: 'line',
                        color: 'rgb(255,0,0)',
                    }]
                };
                charts1.setOption(option1);
            }
        },
        'error': function (err) {
            console.log(err)
            layer.alert('网络异常')
        }
    })


    var charts2 = echarts.init(document.getElementById('dd_nl'), 'dark');
    var option2 = {

        title: {
            text: '各电池堆调度能力分布图'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            orient: 'vertical',
            top: '20%',
            left: '80%',
            data: ['规范要求', '1#电池堆', '2#电池堆', '3#电池堆', '4#电池堆']
        },
        radar: [{
            indicator: [
                {
                    text: '高低压故障\n穿越能力',
                    max: 1.5,
                },
                {
                    text: '动态响应\n能力',
                    max: 1.5,
                },
                {
                    text: '过电流能力',
                    max: 1.5,
                },

                {
                    text: '有功调节\n能力',
                    max: 1.5
                }
            ],
            center: ['40%', '55%'],
            radius: 120
        },

        ],
        series: [{
            type: 'radar',
            tooltip: {
                trigger: 'item'
            },

            data: [{
                value: [1, 1, 1, 1],
                name: '规范要求',

                areaStyle: {
                    type: 'default'


                },
            }, {
                value: [1.2, 1.12, 1.05, 1.1],
                name: '1#电池堆'
            }, {
                value: [1.1, 1.06, 1.1, 1.08],
                name: '2#电池堆'
            }, {
                value: [1.2, 1.12, 1.09, 1.06],
                name: '3#电池堆'
            }, {
                value: [0.9, 1.05, 1.12, 0.9],
                name: '4#电池堆'
            }]
        },

        ]

    };
    charts2.setOption(option2);


    var charts3 = echarts.init(document.getElementById('gonglv'), 'dark');
    var giftImageUrl =
        '';

    var option3 = {
        backgroundColor: 'rgb(27,29,40)',
        title: {
            x: 'center',
            text: '每个电池堆充电功率\n在安全范围且总和最小'
        },
        graphic: {
            elements: [{
                type: 'image',
                style: {
                    image: giftImageUrl,
                    width: 125,
                    height: 125
                },
                left: 'center',
                top: 'center',
            }, {
                type: 'text',
                style: {
                    text: '启动',
                    textAlign: 'center',
                    textVerticalAlign: 'middle',
                    font: ' bolder  1.7em "Microsoft YaHei", sans-serif',
                    fill: 'rgb(158,73,71)',

                },
                left: 'center',
                top: 'center',
                onclick: function () {
                    dlgIndex = layer.open({
                        title: '约束设置',
                        resize: false, //拉伸
                        scrollbar: false,
                        type: 1,
                        shade: [0.5, '#393D49'],
                        skin: 'layui-layer-rim', //加上边框
                        area: ['980px', '700px'], //宽高
                        content: dlg
                    });
                },
            }]
        },
        legend: {
            orient: 'vertical',
            x: '70%',
            y: 'center',
            itemWidth: 20,
            itemHeight: 20,
            align: 'left',
            textStyle: {
                fontSize: 14,
                color: '#fff'
            },
            data: ['系统安全', '供电可靠', '电池损耗', '整体能耗']
        },
        series: [{
            type: 'pie',
            hoverAnimation: false,
            radius: ['40%', '55%'],
            center: ['50%', '50%'],
            color: ['#9D4745', '#9ED35A', '#B48A43', '#3D6FAF'],
            data: [{
                name: '整体能耗',
                value: 3
            }, {
                name: '电池损耗',
                value: 7
            }, {
                name: '供电可靠',
                value: 15
            }, {
                name: '系统安全',
                value: 75
            }],

            label: {
                normal: {
                    show: false,
                }
            }
        }]
    };
    charts3.setOption(option3);


    //判断单选框

    $('input:radio[name="soc"]').change(function () {
        if (this.value == 'zidong1') {
            $('#tr1').hide();
        } else if (this.value == 'zdy1') {
            $('#tr1').show();
        }
    });


    $('input:radio[name="gonglv"]').change(function () {
        if (this.value == 'zidong2') {
            $('#tr2').hide();
        } else if (this.value == 'zdy2') {
            $('#tr2').show();
        }
    });

    $('input:radio[name="reliang"]').change(function () {
        if (this.value == 'zidong3') {
            $('#tr3').hide();
        } else if (this.value == 'zdy3') {
            $('#tr3').show();
        }
    });
    $('input:radio[name="yzx"]').change(function () {
        if (this.value == 'zidong4') {
            $('#tr4').hide();
        } else if (this.value == 'zdy4') {
            $('#tr4').show();
        }
    });
    /**
     * 点击启动按钮btnStart
     */

    $('#btnStart').on('click', function () {
        dlg.hide();
        jdtIndex = layer.open({
            title: '数据正在加载中...',
            type: 1,
            area: ['1000px', '700px'], //宽高
            content: jdt
        });
        draw();
    })

    //进度条
    //Set animation frame
    window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame;


    var canvas = $('#canvas')[0],
        ctx = canvas.getContext('2d'),
        canvasW = 980,
        canvasH = 600;

    ctx.fillStyle = 'black';
    canvas.width = canvasW;
    canvas.height = canvasH;

    var mouse = {
        x: canvasW / 2,
        y: canvasH / 2,
        dx: 0,
        dy: 0
    };

    var emitter = {
        h: 50,
        x: canvasW / 2 - 250,
        y: canvasH / 2,
        vx: 5,
        vy: 5,
        v: 0.05,
        dx: 0,
        dy: 0
    };

    var stops = [50, 500],
        stopIndex = 0,
        delay = 0,
        prog = 0;

    var circle = {
        radius: 125,
        angle: 0
    };

    var particles = new Array();

    var rate = 2,
        time = 0,
        frameIndex = rate;

    var simplex = new SimplexNoise(),
        simplexVal = 0,
        simplexStart = 20;

    //Start loop
    //draw();

    //Draw
    function draw() {

        ctx.globalCompositeOperation = 'source-over';
        ctx.fillStyle = 'rgba(35,37,49,0.5)';
        ctx.fillRect(0, 0, canvasW, canvasH);
        ctx.globalCompositeOperation = 'lighter';

        //Draw loading
        ctx.fillStyle = '#000';
        ctx.fillRect(canvasW / 2 - 250, emitter.y - emitter.h / 2, 500, emitter.h);
        ctx.strokeStyle = 'rgba(0,255,0,0.5)';
        ctx.strokeRect(canvasW / 2 - 250, emitter.y - emitter.h / 2, 500, emitter.h);
        ctx.font = '20pt Arial';
        ctx.fillStyle = 'rgba(0,255,0,0.5)';
        ctx.fillText(Math.floor(prog / 5) + '%', canvasW / 2 - 20, canvasH / 2 + 10);

        //Move emitter
        //console.log(stops[stopIndex] + ' ' + prog + ' ' + delay);
        if (stops[stopIndex] == prog) {
            stopIndex++;
            delay = 50;
        } else if (stops[stopIndex] == undefined) {
            layer.close(jdtIndex);
            $('#jdt').hide();
            dlg.show();
            $('#startDiv').hide();
            $('#pushDiv').show();
            $('#chart').show();
            //获取曲线数据
            $.ajax({
                'url': ctxPath + '/optimization/curve/data?_t=' + new Date().getTime(),
                'type': 'post',
                'dataType': 'json',
                'success': function (res) {
                    if (res.statusCode == 200) {
                        var second = res.data.second;
                        var one = res.data.one;
                        var two = res.data.two;
                        var three = res.data.three;
                        var four = res.data.four;
                        //数据接收展示
                        charts4 = echarts.init(document.getElementById('quxian'), 'dark')
                        var option4 = {
                            title: {
                                text: '优化曲线'
                            },
                            tooltip: {
                                trigger: 'axis'
                            },
                            legend: {
                                bottom: '3%',
                                textStyle: {
                                    color: '#fff',
                                },
                                data: ['1#电池堆', '2#电池堆', '3#电池堆', '4#电池堆']
                            },

                            xAxis: [{
                                type: 'category',
                                boundaryGap: false,
                                splitLine: {
                                    show: false
                                },
                                axisLabel: {
                                    show: false,
                                },
                                data: second
                            }],
                            yAxis: [{
                                type: 'value',
                                splitLine: {
                                    show: false
                                },
                            }],
                            series: [{
                                symbol: "none",
                                name: '1#电池堆',
                                type: 'line',
                                smooth: 0.5,
                                symbolSize: 8,
                                color: 'rgb(255,0,0)',
                                data: one
                            }, {
                                symbol: "none",
                                name: '2#电池堆',
                                type: 'line',
                                smooth: 0.5,
                                symbolSize: 8,
                                color: 'rgb(0,255,0)',
                                data: two
                            }, {
                                symbol: "none",
                                name: '3#电池堆',
                                type: 'line',
                                smooth: 0.5,
                                symbolSize: 8,
                                color: 'rgb(0,0,255)',
                                data: three
                            }, {
                                symbol: "none",
                                name: '4#电池堆',
                                type: 'line',
                                smooth: 0.5,
                                symbolSize: 8,
                                color: 'rgb(255,255,0)',
                                data: four
                            }]
                        };

                        charts4.setOption(option4);
                    }
                },
                'error': function (err) {
                    layer.alert('网络异常')
                }
            })

            return;
        } else {
            if (delay == 0 && prog < stops[stopIndex]) {
                emitter.dx = -1;
                emitter.x += 2;
                prog += 2;
            } else {
                emitter.dx = 0;
                delay--;
            }
        }

        //Draw emitter
        ctx.fillStyle = '#0f0';
        ctx.fillRect(emitter.x, emitter.y - emitter.h / 2, 1, emitter.h);

        //Draw particles
        var i = 0;
        for (i in particles) {
            var p = particles[i];

            //Check if die
            if (time > p.die) {
                p.o -= 0.01;
                if (p.o < 0) {
                    particles.splice(i, 1);
                }
            }

            //Add v
            p.x += p.vx;
            p.y += p.vy;

            //Add source move
            p.x += p.sourcedx / 10;
            p.y += p.sourcedy / 10;

            //Simplex noise
            if (p.simplexIndex > simplexStart) {
                p.simplexVal = simplex.noise3D(p.x / 100, p.y / 100, time / 100);
            }

            p.simplexIndex++;
            p.x += p.simplexVal;
            p.y += p.simplexVal;

            //If (almost) outside canvas
            if (p.x < 0 + 20 || p.x > canvasW - 20) {
                p.vx *= -1.015;
            }
            if (p.y < 0 + 20 || p.y > canvasH - 20) {
                p.vy *= -1.015;
            }

            ctx.beginPath();
            ctx.fillStyle = 'rgba(0, ' + p.green + ', 0, ' + p.o + ')';
            ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, true);
            ctx.fill();
            ctx.save();
        }

        //if emitter is moving
        if (emitter.dx !== 0) {
            for (var i = 0; i < rate; i++) {
                //Create particle
                var particle = {
                    x: emitter.x,
                    y: emitter.y + (Math.random() * emitter.h - emitter.h / 2),
                    r: Math.random() + 0.5,
                    vx: (Math.random() * -2),
                    vy: (Math.random() - 0.5),
                    o: 1,
                    birth: time,
                    die: time + (Math.random() * 50 + 50), //1+1),
                    sourcedx: emitter.dx,
                    sourcedy: emitter.dy,
                    red: Math.round(Math.random() * 255),
                    green: Math.round(Math.random() * 255),
                    blue: Math.round(Math.random() * 255),
                    simplexVal: 0,
                    simplexIndex: 0
                };

                particles.push(particle);
            }
        }

        time++;
        window.requestAnimationFrame(draw);

    }

    $(window).mousemove(function (e) {
        mouse.dx = e.pageX - mouse.x;
        mouse.dy = e.pageY - mouse.y;

        mouse.x = e.pageX;
        mouse.y = e.pageY;
    });


    /**
     * 点击策略下发
     */
    $('#btnPush').on('click', function () {
        layer.confirm('调度优化策略下发到iRouter？', {
            btn: ['是', '否'] //按钮
        }, function () {

            $.ajax({
                'url': ctxPath + '/cmd/push',
                'type': 'post',
                'dataType': 'json',
                'data': {},
                'success': function (data) {
                    if (data.statusCode == 200) {
                        //$('#btnPush').attr('disabled', true);
                        //$('#btnPush').html('策略 <br/> 下发 <br/>  成功');
                        layer.alert(data.msg);
                    } else if (data.statusCode == 500) {
                        layer.alert(data.msg);
                        return;
                    } else {
                        layer.alert('网络异常');
                    }
                },
                'error': function (error) {
                    layer.alert('网络异常');
                }
            });
        }, function () {

        });

    })
    window.addEventListener("resize", function () {
        if (charts1) {
            charts1.resize();
        }
        charts2.resize();
        charts3.resize();
        if (charts4) {
            charts4.resize();
        }


    });

})
